

<template>
    <div class="sdy-login">
    <SdyHeader title="啥都有 ~ 登录" back></SdyHeader>
    <van-form class="login-form" @submit="submitHandler">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名', pattern: /\w{6,12}/ }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div>
        还没有账号? <router-link to="/register">去注册</router-link>
      </div>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>



<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter,type Router } from 'vue-router';
import {loginApi} from '@/api/users'
import { Toast } from 'vant'

const $router:Router =  useRouter()
const username = ref<string>('')
const password = ref<string>('')

const submitHandler = async ()=>{
    const res = await loginApi(username.value,password.value)
    console.log(res)
  // 判断结果
  // 表示登录成功
  if (((res as unknown) as { code: string }).code === '200') {
    Toast({
      message: '登录成功',
      icon: 'phone-circle-o',
    })
    // 储存一下登录的信息包括 token 和 username
    // 登录成功后会自动生成一个token 和 id 并把它存到仓库
    window.localStorage.setItem('token',res.data.token)
    window.localStorage.setItem('user_id',res.data.userid)
    
    // 登录成功再进行页面跳转
    setTimeout(()=>{
      // 跳转
      $router.push({path:'/home'})
    },1500)
     return
  }

   // 代码执行到这里, 说明手机号不行
   Toast({
    message: '登录失败',
    icon: 'phone-circle-o',
  })
}

</script>




<style scoped lang="scss">
.sdy-login {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  > .login-form {
    border: 1px solid #333;
    border-radius: 10px;
  }
}
</style>